//
//  LYUserAccountViewModel.swift
//  Sina_Weibo2
//
//  Created by Elsevier on 16/5/14.
//  Copyright © 2016年 Yang Lu. All rights reserved.
//

import UIKit

class LYUserAccountViewModel: NSObject {
    
    static let sharedInstance: LYUserAccountViewModel = LYUserAccountViewModel()
    
    let userAccountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask,true).last! + "/account.plist"
    
    ///账号
    var userAccount: LYUserAccount?
    
    //用户是否登录的属性
    var isUserLogin: Bool {
        get{
            return  userAccount != nil
        }
    }
    
    override init() {
        super.init()
        
        /// 加载沙盒里面的账号
        userAccount = loadUserAccount()
    }
    
    
    func loadAccessToken(code: String,callback:(error: NSError?) -> ()) {
        let urlString = "oauth2/access_token"
        //参数
        let parameters = [
            "client_id" : client_id,
            "client_secret" : client_secret,
            "grant_type" : "authorization_code",
            "code" : code,
            "redirect_uri": redirect_uri
        ]
    
        LYNetworkTool.sharedInstance.request(RequestMethod.POST, URLString: urlString, parameters: parameters, success: { (task, responseObject) -> Void in
            LYPrint(items: "获取AccessToken成功: \(responseObject)")
            
            // 判断返回的数据是否能够转成字典
            if let result = responseObject as? [String: AnyObject] {
                // 字典转模型
                let userAccount = LYUserAccount(dict: result)
                LYPrint(items: "userAccount: \(userAccount)")
                
                LYPrint(items: "userAccountPath: \(self.userAccountPath)")
                
                // 调用归档的方法,将模型归档到沙盒里面
                NSKeyedArchiver.archiveRootObject(userAccount, toFile: self.userAccountPath)
                
                // 将账号赋值给属性
                self.userAccount = userAccount
                
                // 告诉控制器,模型保存完成了
                callback(error: nil)
            } else {
                LYPrint(items: "返回数据转字典失败了")
            }
            
            }, failure: { (task, error) -> Void in
                callback(error: error)
        })
    }

    
    
        
        //解档账号
        func loadUserAccount() -> LYUserAccount?
        {
            
            if let userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(self.userAccountPath) as? LYUserAccount
            {
                if userAccount.expiresDate?.compare(NSDate()) != NSComparisonResult.OrderedAscending {
                    // 没有过期
                    LYPrint(items: "没有过期")
                    return userAccount
                } else {
                    return nil
                }
            } else {
                //没有加载出账号
                return nil
            }
        }
}